#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <sys/wait.h>

int main()
{
    extern char **environ;

    while(1) {
        printf("[username@hostname]$ ");
        fflush(stdout);

        char input[1024] = {0};
        fgets(input, 1023, stdin);//从标准输入读取一行数据，数据量不能大于1023字节
        input[strlen(input) - 1] = '\0';

        printf("[%s]\n", input);

        char *ptr = input;
        char *argv[32] = {NULL};
        int argc = 0;
        while(*ptr != '\0') {
            if (*ptr == ' ') {ptr++;  continue;}
            argv[argc] = ptr;
            argc++;
            while(*ptr != '\0' && *ptr != ' ') { ptr++; }
            *ptr = '\0';
            ptr++;
        }
        argv[argc] = NULL;
        for (int i = 0; argv[i] != NULL; i++) {
            printf("[%s]\n", argv[i]);
        }

        pid_t pid = fork();
        if (pid == 0) {
            execvp(argv[0], argv);
            exit(-1);//替换失败则让子进程退出，不要成为第二shell
        }
        wait(NULL);//进程等待
    }
    return 0;
}

